<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏房间</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_room.css">
</head>
<body>
    <div class="nav">网络五子棋对战游戏</div>
    <div class="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="450px" height="450px"></canvas>
            <!-- 显示区域 -->
            <div id="screen"> 等待玩家连接中... </div>
        </div>
        <div id="chat_area" width="400px" height="300px">
            <div id="chat_show">
                <p id="self_msg">你好！</p></br>
                <p id="peer_msg">你好！</p></br>
            </div>
            <div id="msg_show">
                <input type="text" id="chat_input">
                <button id="chat_button">发送</button>
            </div>
        </div>
    </div>
    <script>
    
        //房间前端与后端建立websocket长连接
        var ws_url = "ws://"+ location.host + "/room";
        var ws_hdl = new WebSocket(ws_url);

        var room_info = null;//用于保存房间的信息
        var is_me;//用于判断是否是自己下棋

        let chessBoard = [];
        let BOARD_ROW_AND_COL = 15;
        let chess = document.getElementById('chess');
        //获取chess控件区域2d画布
        let context = chess.getContext('2d');
        function initGame() {
            initBoard();
            // 背景图片
            let logo = new Image();
            logo.src = "image/sky.jpeg";
            logo.onload = function () {
                // 绘制图片
                context.drawImage(logo, 0, 0, 450, 450);
                // 绘制棋盘
                drawChessBoard();
            }
        }
        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            context.strokeStyle = "#BFBFBF";
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                //横向的线条
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 430); 
                context.stroke();
                //纵向的线条
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30); 
                context.stroke();
            }
        }
        //绘制棋子
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            //createLinearGradient() 方法创建放射状/圆形渐变对象
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            // 区分黑白子
            if (!isWhite) {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            } else {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#F9F9F9");
            }
            context.fillStyle = gradient;
            context.fill();
        }
        //棋盘区域的点击事件
        chess.onclick = function (e) {
            //判断是否是自己下棋
            if(!is_me)
            {
                alert("此时轮到对方下棋!");
                return;
            }
            let x = e.offsetX;
            let y = e.offsetY;
            // 注意, 横坐标是列, 纵坐标是行
            // 这里是为了让点击操作能够对应到网格线上
            let col = Math.floor(x / 30);
            let row = Math.floor(y / 30);
            if (chessBoard[row][col] != 0) {
                alert("当前位置已有棋子！");
                return;
            }
            //oneStep(col, row, true);
            //向服务器发送响应，服务器接收到响应后，才能绘制棋子
            send_chess(row,col);
        }

        function send_chess(r,c){
            //发送一个json类型的请求
            var chess_info = {
                optype: "put_chess",
                room_id: room_info.room_id,
                uid: room_info.uid,
                row: r,
                col: c
            };
            ws_hdl.send(JSON.stringify(chess_info));
            console.log("chick: "+ JSON.stringify(chess_info));
        }

        
        
        window.onbeforeunload = function() {
            ws_hdl.close();
        }

        //建立成功之后，函数处理
        ws_hdl.onopen = function(){
            console.log("房间长连接建立成功!");
        }

        ws_hdl.onclose = function(){
            console.log("房间长连接断开成功!");
        }

        ws_hdl.onerror = function() {
            console.log("房间长连接出错!");
        }

        function set_screen(is_me) {
            var screen_div = document.getElementById("screen");
            if(is_me == true)
            {
                screen_div.innerHTML = "轮到己方走棋!";
            }
            else
            {
                screen_div.innerHTML = "轮到对方走棋!";
            }
        }

        ws_hdl.onmessage = function(evt) {
            //alert(evt.data);
            var info = JSON.parse(evt.data);
            console.log(JSON.stringify(info));
            if(info.optype == "room_ready")
            {
                room_info = info;//此时是房间信息
                //判断这个棋子是白棋还是黑棋
                is_me = info.uid == info.white_id ? true:false;
                //处理按钮的事件
                set_screen(is_me);
                initGame()
            }
            else if(info.optype == "put_chess")
            {
                console.log("put_chess: " + JSON.stringify(info));
                //此时是一个下棋消息
                if(info.result == false)
                {
                    alert(info.reason);
                    return;
                }
                //判断当前是否是我走棋，走棋之后就是对方走棋
                is_me = info.uid == room_info.uid ? false : true;
                //棋子的颜色确定
                isWhite = info.uid == room_info.white_id ? true:false;
                //绘制棋子
                if(info.row != -1 && info.col != -1)
                {
                    oneStep(info.col,info.row,isWhite);
                    //设置棋盘信息
                    chessBoard[info.row][info.col] = 1;
                }
                //判断是否有胜利者
                if(info.winner == 0)
                {
                    return;
                }
                //此时有胜利者,向框中嵌入原因
                var screen_div = document.getElementById("screen");
                if(info.winner == room_info.uid)
                {
                    screen_div.innerHTML = info.reason;
                }
                else
                {
                    screen_div.innerHTML = "对方五星连珠了,你还是输了,下次努力吧!";
                }
                //此时处理返回大厅的逻辑
                var chess_area_div = document.getElementById("chess_area");
                var butto_div = document.createElement("div");//一个按钮
                butto_div.innerHTML = "点击返回游戏大厅";
                butto_div.onclick = function (){
                    ws_hdl.close();
                    location.replace("/game_hall.html");
                }
                //嵌入到子框中
                chess_area_div.appendChild(butto_div);
            }
            else if(info.optype == "chat")
            {
                //处理服务器发送的聊天逻辑
                if(info.result == false)
                {
                    alert(info.reason);
                    return;
                }
                //设置消息的格式
                var msg_div = document.createElement("p");
                msg_div.innerHTML = info.message;
                if(info.uid == room_info.uid)
                {
                    //是自身的消息
                    msg_div.setAttribute("id","self_msg");
                }
                else
                {
                    msg_div.setAttribute("id","peer_msg");
                }

                var br_div = document.createElement("br");
                //获取聊天控件
                var show_msg_div = document.getElementById("chat_show");
                show_msg_div.appendChild(msg_div);
                show_msg_div.appendChild(br_div);
                document.getElementById("chat_input").value = "";
            }
        }

        //前端界面向后端发送聊天框消息处理
        //1、给发送框添加点击事件，获取到聊天框中的内容
        //2、组织成json格式发送给后端
        var cb = document.getElementById("chat_button");
        cb.onclick = function(){
            var send_msg = {
                optype: "chat",
                room_id: room_info.room_id,
                uid: room_info.uid,
                message: document.getElementById("chat_input").value
            };
            ws_hdl.send(JSON.stringify(send_msg));
        }
    </script>
</body>
</html>